package com.atguigu.edu.realtime.app.dws.trade;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.app.BaseAppV1;
import com.atguigu.edu.realtime.bean.TradeProvinceOrderBean;

import com.atguigu.edu.realtime.common.Constant;
import com.atguigu.edu.realtime.function.DimAsyncFunction;
import com.atguigu.edu.realtime.util.AtguiguUtil;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;


/**
 * @description: TODO
 * @author: liminghui
 * @create: 2022/9/1 15:42
 */
public class DwsTradeProvinceOrderWindow extends BaseAppV1 {

    public static void main(String[] args) {
        new DwsTradeProvinceOrderWindow().init(
                3001,
                2,
                "DwsTradeProvinceOrderWindow",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {

        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderDetailId(stream);
        //distinctedStream.print();

        SingleOutputStreamOperator<TradeProvinceOrderBean> beanStream = parseToPojo(distinctedStream);
        //beanStream.print();

        SingleOutputStreamOperator<TradeProvinceOrderBean> beanStreamWithoutDim = windowAndAgg(beanStream);
        //beanStreamWithoutDim.print();

        SingleOutputStreamOperator<TradeProvinceOrderBean> beanStreamWithDim = addDim(beanStreamWithoutDim);
        //beanStreamWithDim.print();

        beanStreamWithDim
                .print();
/*                .map(bean->JSON.toJSONString(bean))
                .addSink(FlinkSinkUtil.getDorisSink("edu.dws_trade_province_order_window"));*/
    }

    private SingleOutputStreamOperator<TradeProvinceOrderBean> addDim(SingleOutputStreamOperator<TradeProvinceOrderBean> beanStreamWithoutDim) {

        SingleOutputStreamOperator<TradeProvinceOrderBean> provinceStream = AsyncDataStream
                .unorderedWait(
                        beanStreamWithoutDim,
                        new DimAsyncFunction<TradeProvinceOrderBean>() {
                            @Override
                            public String getTable() {
                                return "dim_base_province";
                            }

                            @Override
                            public String getId(TradeProvinceOrderBean input) {
                                return input.getProvinceId();
                            }

                            @Override
                            public void addDim(JSONObject dim, TradeProvinceOrderBean bean) {

                                bean.setProvinceName(dim.getString("NAME"));
                            }
                        },
                        60,
                        TimeUnit.SECONDS
                );
        return provinceStream;
    }

    private SingleOutputStreamOperator<TradeProvinceOrderBean> windowAndAgg(SingleOutputStreamOperator<TradeProvinceOrderBean> beanStream) {
        return

        beanStream

                //TODO 测试使用
                .map(json->{
                    System.out.println(json);
                    return json;
                })

                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<TradeProvinceOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs())
                )

                .keyBy(TradeProvinceOrderBean::getProvinceId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradeProvinceOrderBean>() {
                            @Override
                            public TradeProvinceOrderBean reduce(TradeProvinceOrderBean bean1,
                                                                 TradeProvinceOrderBean bean2) throws Exception {
                                bean1.setFinalAmount(bean1.getFinalAmount().add(bean2.getFinalAmount()));
                                return bean1;
                            }
                        },
                        new ProcessWindowFunction<TradeProvinceOrderBean, TradeProvinceOrderBean, String, TimeWindow>(){
                            @Override
                            public void process(String s,
                                                Context ctx,
                                                Iterable<TradeProvinceOrderBean> elements,
                                                Collector<TradeProvinceOrderBean> out) throws Exception {

                                TradeProvinceOrderBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                                bean.setCurDate(AtguiguUtil.toDate(ctx.window().getStart()));

                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<TradeProvinceOrderBean> parseToPojo(SingleOutputStreamOperator<JSONObject> distinctedStream) {
        return
        distinctedStream
                .map(new MapFunction<JSONObject, TradeProvinceOrderBean>() {
                    @Override
                    public TradeProvinceOrderBean map(JSONObject value) throws Exception {

                        String amount = value.getString("final_amount");
                        BigDecimal final_amount = new BigDecimal(0);
                        
                        if (amount!=null){
                            final_amount=new BigDecimal(amount);
                        }
                        return TradeProvinceOrderBean
                                .builder()
                                .provinceId(value.getString("province_id"))
                                .finalAmount(final_amount)
                                .ts(value.getLong("ts")*1000)

                                .build();
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        //stream.print();

        return

        stream
                .map(json-> JSON.parseObject(json))
                .keyBy(obj->obj.getString("id"))
                .process(
                        new KeyedProcessFunction<String, JSONObject, JSONObject>() {

                            private ValueState<JSONObject> maxTsDateState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                maxTsDateState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("maxTsDateState", JSONObject.class));

                            }

                            @Override
                            public void processElement(JSONObject value,
                                                       Context ctx,
                                                       Collector<JSONObject> out) throws Exception {
                                if (maxTsDateState.value() == null) {
                                    maxTsDateState.update(value);

                                    ctx.timerService().registerProcessingTimeTimer(
                                            ctx.timerService().currentProcessingTime()+5000L
                                    );

                                }else {

                                    String last = maxTsDateState.value().getString("row_op_ts");

                                    String current = value.getString("row_op_ts");

                                    if (AtguiguUtil.isLarger(current,last)){
                                        maxTsDateState.update(value);
                                    }
                                }

                            }

                            @Override
                            public void onTimer(long timestamp,
                                                OnTimerContext ctx,
                                                Collector<JSONObject> out) throws Exception {
                                out.collect(maxTsDateState.value());


                            }
                        }
                );
    }
}
